package com.meepo.basic.upgrader

import android.util.Log
import android.widget.Toast
import androidx.fragment.app.FragmentActivity
import com.meepo.basic.API
import com.meepo.basic.schema.common.ResponseWrapper
import com.meepo.framework.design.upgrade.AppUpgrader
import com.meepo.framework.design.upgrade.listener.IUpgradeListener
import com.meepo.sdk.component.observer.Observer
import com.meepo.sdk.component.observer.ObserverManager.applySchedulers

object Upgrader {

    fun tryUpgrade(activity: FragmentActivity) {
        tryUpgrade(activity, false)
    }

    fun tryUpgrade(activity: FragmentActivity, force: Boolean) {
        API.get().fetchUpgradeInfo()
            .applySchedulers()
            .subscribe(object : Observer<ResponseWrapper<AppUpgrade>>() {
                override fun onSuccess(t: ResponseWrapper<AppUpgrade>?) {
                    t?.data?.let { upgrade ->
                        AppUpgrader.Builder(activity)
                            .setApkFileUrl(upgrade.apkFileUrl)
                            .setConstraint(upgrade.constraint)
                            .setUpdate(upgrade.update)
                            .setIgnorable(if (force) false else upgrade.ignorable)
                            .setUpgradeLog(upgrade.upgradeLog)
                            .setTargetSize(upgrade.targetSize)
                            .setNewVersion(upgrade.newVersion)
                            .setTitle(upgrade.title)
                            .setUpgradeListener(object : IUpgradeListener {
                                override fun onBefore(updateApp: AppUpgrader) {
                                }

                                override fun onCancel(updateApp: AppUpgrader) {
                                }

                                override fun onIgnore(updateApp: AppUpgrader) {

                                }

                                override fun onNoNewVersion(appUpgrader: AppUpgrader) {
                                    if (force) {
                                        Toast.makeText(activity, "当前已是最新版本", Toast.LENGTH_SHORT)
                                            .show();
                                    }
                                }

                                override fun onConfirm(appUpgrader: AppUpgrader) {

                                }

                                override fun onShowDialog(appUpgrader: AppUpgrader) {
                                    appUpgrader.showDialogFragment()

                                }

                                override fun onError(throwable: Throwable) {
                                }
                            })
                            .build()
                            .upgrade()

                    }
                }

                override fun onFailure(e: Throwable) {
                    Log.e("Upgrader", e.message ?: "")
                }
            })
    }
}